<template>
    <div>
        <panel-head :route="route" />
        <div class="btns">
            <el-button :icon="Plus" type="primary" size="small" @click="open(null)">新增</el-button>
            <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确认删除数据?"
                @confirm="confirmEvent"
            >
                <template #reference>
                    <el-button type="danger" :icon="Delete" size="small">删除</el-button>
                </template>
            </el-popconfirm>
        </div>

        <!-- 展示表格数据 -->
        <el-table :data="tableData.list" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="name" label="昵称" />
            <el-table-column prop="avatar" label="头像" >
                <template #default="scope">
                    <el-image :src="scope.row.avatar" style="width:50px; height:50pz" />
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别" >
                <template #default="scope">
                    {{ scope.row.sex==='1'?'男':'女' }}
                </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" />
            <el-table-column prop="active" label="状态" >
                <template #default="scope">
                    <el-tag :type="scope.row.active===1?'success':'danger'">{{ scope.row.active===1?'正常':'失效' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" >
                <template #default="scope">
                    <div class="flex-box">
                        <el-icon style="margin-right: 10px"><Clock /></el-icon>
                        {{ scope.row.create_time }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" @click="open(scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-info">
            <el-pagination
                v-model:current-page="paginationData.pageNum"
                v-model:page-size="paginationData.pageSize"
                :page-sizes="[10, 30, 50]"
                size="small"
                :background="false"
                layout="sizes, prev, pager, next, total"
                :total="tableData.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 添加陪诊师弹框 -->
        <el-dialog
            v-model="dialogFormVisible"
            :before-close="beforeClose"
            title="编辑用户"
            width="500"
        >
            <!-- 添加陪诊师表单 -->
            <el-form
                ref="formRef"
                :model="form"
                label-width="100px"
                label-position="left"
                :rules="rules"
            >
                <el-form-item prop="id" v-show="false">
                    <el-input v-model="form.id"></el-input>
                </el-form-item>
                <el-form-item prop="name" label="昵称">
                    <el-input v-model="form.name" placeholder="请填写昵称" />
                </el-form-item>
                <el-form-item prop="avatar" label="头像">
                    <el-button v-if="!form.avatar" type="primary" @click="dialogImageVisible = true">上传头像</el-button>
                    <el-image v-else :src="form.avatar" style="width:100px;height:100px" />
                </el-form-item>
                <el-form-item prop="sex" label="性别">
                    <el-select v-model="form.sex" placeholder="请选择性别">
                        <el-option label="男" value="1" />
                        <el-option label="女" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="age" label="年龄">
                    <el-input-number v-model="form.age" :min="18" :max="50" />
                </el-form-item>
                <el-form-item prop="mobile" label="手机号">
                    <el-input v-model="form.mobile" placeholder="请填写手机号" />
                </el-form-item>
                <el-form-item prop="active" label="是否生效">
                    <el-radio-group v-model="form.active">
                        <el-radio :value="1">生效</el-radio>
                        <el-radio :value="0">失效</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible= false">取消</el-button>
                    <el-button type="primary" @click="confirm(formRef)">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 头像选择弹框 -->
        <el-dialog
            v-model="dialogImageVisible"
            @before-close="dialogImageVisible= false"
            title="头像选择"
            width="680"
        >
            <div class="image-list">
                <div v-for="(item, index) in ImageList" :key="item.name"
                    class="img-box"
                    @click="selectIndex = index"
                >
                    <div v-if="selectIndex===index" class="select">
                        <el-icon color='#fff'><Check /></el-icon>
                    </div>
                    <el-image 
                        :src="item.url"
                        style="width:150px; height:150px"
                    ></el-image>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogImageVisible= false">取消</el-button>
                    <el-button type="primary" @click="confirmImage(formRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { Plus, InfoFilled, Delete } from '@element-plus/icons-vue'
import { photoList, companion, companionList, deleteCompanion } from '../../../api'
import { ElMessage } from 'element-plus'
import dayjs from "dayjs";
import { useRoute } from 'vue-router';

const route = useRoute()


const ImageList = ref([])
onMounted(() => {
    photoList().then(({data})=>{
        ImageList.value = data.data
    })
    getListData()
})

// 获取表格数据
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
});
const getListData = ()=>{
    companionList(paginationData).then(({data})=>{
        const {list, total} = data.data
        list.forEach((item) => {
            item.create_time = dayjs(item.create_time).format("YYYY-MM-DD");
        });
        tableData.list = list
        tableData.total = total
    })
}
const tableData = reactive({
  list: [],
  total: 0,
});
// 分页
const handleSizeChange = (val) => {
  paginationData.pageSize = val;
  getListData();
};
const handleCurrentChange = (val) => {
  paginationData.pageNum = val;
  getListData();
};

const selectData= ref([])
const handleSelectionChange= (val)=>{
    selectData.value = val//.map(item=>({id:item.id}))
}

const confirmEvent = ()=>{
    if(selectData.value.length===0){
        return ElMessage.warning('请选择至少一个删除项')
    }
    console.log(selectData.value,'selectData')
    deleteCompanion({id:selectData.value.map(item=>({id:item.id}))}).then(({data})=>{
        if(data.code===10000){
            getListData();
        }
    })
}

// 添加陪诊师弹框
const dialogFormVisible = ref(false)
const beforeClose = ()=>{
    dialogFormVisible.value = false
    formRef.value.resetFields()
}
const open = (rowdata={}) =>{
    dialogFormVisible.value = true
    nextTick(()=>{
        if(rowdata){
            Object.assign(form,rowdata)
        }
    })
}

// 添加陪诊师表单
const formRef= ref()
const form = reactive({
    id:'',
    name:'',
    sex:'1',
    age:28,
    mobile:'',
    avatar:'',
    active:1
})
    // 账号校验规则
const validateUser = (rule, value, callback) => {
  // 不能为空
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    reg.test(value) ? callback() : callback(new Error('手机号格式不对,请输入正确手机号'))
  }
}
const rules = reactive({
  name: [{ required: true, trigger: 'blur', message: '请填写昵称' }],
  avatar:[{ required: true, message: '请选择头像'}],
  sex:[{ required: true, trigger: 'change', message: '请选择性别'}],
  mobile: [{ required: true, validator: validateUser, trigger: 'blur' }]
})

const confirm = async (formEl)=>{
    if(!formEl) return
    await formEl.validate((valid, fields)=>{
        if(valid){
            companion(form).then(({ data })=>{
                if(data.code===10000)
                {
                    ElMessage.success('创建成功')
                    getListData()
                    beforeClose()
                }else{
                    ElMessage.error(data.message)
                }
            })
        }
        else{
            console.log('校验失败', fields)
        }
    })
}

// 头像选择弹框
const dialogImageVisible = ref(false)
const selectIndex = ref(0)
const confirmImage=()=>{
    dialogImageVisible.value = false
    form.avatar = ImageList.value[selectIndex.value].url
}
</script>

<style lang="less" scoped>

.btns {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .img-box {
    position: relative;
    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>